package com.atguigu.gmall.product.init;

import com.atguigu.gmall.common.constant.SysRedisConst;
import com.atguigu.gmall.product.service.SkuInfoService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

@Service
@Slf4j
public class SkuIdBloomInitService {

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private RedissonClient redissonClient;
    @PostConstruct //当前组件创建完成以后
    public void initSkuBloom(){
        //1、查询出所有SkuId
        List<Long> skuIds = skuInfoService.findAllSkuId();
        //2、把所有的Id初始化进布隆过滤器
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(SysRedisConst.BLOOM_SKUID);
        //3、初始化布隆过滤器
        boolean exists = bloomFilter.isExists();
        if (!exists){
            //尝试初始化，如果布隆过滤器没有初始化过，就尝试初始化
            bloomFilter.tryInit(5000000,0.00001);
        }
        //4、把所有商品添加到布隆过滤器中，
        for (Long skuId : skuIds) {
            bloomFilter.add(skuId);
        }

        log.info("布隆初始化完成.....总计添加了{}条数据",skuIds.size());
    }
}
